package com.supersoul.myself.filter;

import com.alibaba.fastjson.JSONObject;
import com.supersoul.myself.entity.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "AuthenticationFilter",urlPatterns = {"/blog/save", "/comment/save", "/category/save", "/blog/person/list", "/blog/delete/", "/category/person/list", "/blog/collection/list", "/blog/collection"})
public class AuthenticationFilter  implements Filter {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("进入AuthenticationFilter...");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            // 传参有问题
            return;
        }
        String tokenJson = stringRedisTemplate.opsForValue().get(token);
        User user = JSONObject.parseObject(tokenJson, User.class);
        if (user == null) {
            // 没有登录过
            return;
        }
        filterChain.doFilter(request,response);
        System.out.println("退出AuthenticationFilter...");
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
